package com.gcloud.controller.compute.workflow.vm.storage;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;

import com.gcloud.controller.compute.dao.InstanceDao;
import com.gcloud.controller.compute.entity.VmInstance;
import com.gcloud.controller.compute.workflow.model.storage.AttachDataDiskFlowCommandReq;
import com.gcloud.controller.compute.workflow.model.storage.AttachDataDiskFlowCommandRes;
import com.gcloud.controller.storage.service.IVolumeService;
import com.gcloud.core.messagebus.MessageBus;
import com.gcloud.core.util.MessageUtil;
import com.gcloud.core.workflow.core.BaseWorkFlowCommand;
import com.gcloud.header.compute.msg.node.vm.storage.DetachDataDiskMsg;
import com.gcloud.header.storage.model.VmVolumeDetail;
import com.gcloud.service.common.compute.uitls.DiskUtil;

import lombok.extern.slf4j.Slf4j;

@Component
@Scope("prototype")
@Slf4j
public class AttachDataDiskFlowCommand extends BaseWorkFlowCommand {

	@Autowired
	private MessageBus bus;

	@Autowired
	private InstanceDao instanceDao;
	
	@Autowired
	private IVolumeService volumeService;

	@Override
	protected Object process() throws Exception {
		AttachDataDiskFlowCommandReq req = (AttachDataDiskFlowCommandReq) getReqParams();
		log.debug(String.format("虚拟机%s 挂载数据盘块设备开始", req.getInstanceId()));
		
		VmVolumeDetail volumeDetail = req.getVolumeDetail();
		
		volumeService.attachVolume(volumeDetail.getVolumeId(), req.getInstanceId(), DiskUtil.getDeviceMountpoint(volumeDetail.getTargetDev()), req.getVmHostName(), getTaskId());

		log.debug(String.format("虚拟机%s 挂载数据盘块设备结束", req.getInstanceId()));
		return null;
	}

	@Override
	protected Object rollback() throws Exception {

		AttachDataDiskFlowCommandReq req = (AttachDataDiskFlowCommandReq) getReqParams();

		VmInstance ins = instanceDao.getById(req.getInstanceId());

		DetachDataDiskMsg msg = new DetachDataDiskMsg();
		msg.setTaskId(getTaskId());
		msg.setInstanceId(req.getInstanceId());
		msg.setVolumeDetail(req.getVolumeDetail());
		msg.setServiceId(MessageUtil.computeServiceId(ins.getHostname()));

		bus.send(msg);

		return null;
	}

	@Override
	protected Object timeout() throws Exception {
		return null;
	}

	@Override
	protected Class<?> getReqParamClass() {
		return AttachDataDiskFlowCommandReq.class;
	}

	@Override
	protected Class<?> getResParamClass() {
		return AttachDataDiskFlowCommandRes.class;
	}
}
